package com.ruoyi.site.controller;

import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.site.vo.InstantBuyRequest;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.site.domain.OrderDetails;
import com.ruoyi.site.service.IOrderDetailsService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.framework.web.service.TokenService;

import static com.ruoyi.common.utils.ServletUtils.getRequest;

/**
 * 订单详情Controller
 * 
 * @author chuckeytang
 * @date 2025-08-17
 */
@RestController
@RequestMapping("/site/orders")
public class OrderDetailsController extends BaseController
{
    @Autowired
    private IOrderDetailsService orderDetailsService;

    @Autowired(required = false)
    private TokenService tokenService;

    /**
     * 查询订单详情列表
     */
    @PreAuthorize("@ss.hasPermi('site:details:list')")
    @GetMapping("/list")
    public TableDataInfo list(OrderDetails orderDetails)
    {
        startPage();
        List<OrderDetails> list = orderDetailsService.selectOrderDetailsList(orderDetails);
        return getDataTable(list);
    }


    /**
     * 查询当前用户的订单列表 (前台用户接口)
     * * 注意：这里假设通过 Spring Security 或 TokenService 可以获取到当前登录的前台用户的 userId。
     * 实际项目中，需要根据您前台用户认证的具体实现（如 OAuth2/JWT）来获取用户ID。
     */
    @GetMapping("/user/my-orders")
    public TableDataInfo listUserOrders()
    {
        Long currentUserId = null;
        try {
            LoginUser loginUser = tokenService.getLoginUser(getRequest());
            if (loginUser != null) {
                // 假设若依的 LoginUser 中存储了前台用户的 user_id
                // 如果 LoginUser 对应的是 sys_user (管理员)，则需要一个单独的前台用户体系来获取 ID
                // 在这个示例中，我们假设您能够从会话或Token中解析出前台用户ID (Long)
                // 简单起见，我们假设前台用户ID可以直接从 LoginUser 获取
                currentUserId = loginUser.getUserId(); // 这里的 userId 应该是 users 表中的 ID
            }
        } catch (Exception e) {
            // 捕获异常，用户未登录或Token无效
            return getDataTable(null); // 返回空列表
        }

        if (currentUserId == null) {
            return getDataTable(null); // 用户未登录
        }

        startPage();
        List<OrderDetails> list = orderDetailsService.selectOrderDetailsListByUserId(currentUserId);
        return getDataTable(list);
    }

    /**
     * 导出订单详情列表
     */
    @PreAuthorize("@ss.hasPermi('site:details:export')")
    @Log(title = "订单详情", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, OrderDetails orderDetails)
    {
        List<OrderDetails> list = orderDetailsService.selectOrderDetailsList(orderDetails);
        ExcelUtil<OrderDetails> util = new ExcelUtil<OrderDetails>(OrderDetails.class);
        util.exportExcel(response, list, "订单详情数据");
    }

    /**
     * 获取订单详情详细信息
     */
    @GetMapping(value = "/{orderId}")
    public AjaxResult getInfo(@PathVariable("orderId") Long orderId)
    {
        Long currentUserId = null;
        try {
            LoginUser loginUser = tokenService.getLoginUser(getRequest());
            currentUserId = loginUser.getUserId();
        } catch (Exception e) {
            return AjaxResult.error("用户未登录或会话无效");
        }

        OrderDetails order = orderDetailsService.selectOrderDetailsByOrderId(orderId);

        if (order == null) {
            return AjaxResult.error("订单不存在");
        }

        if (!order.getUserId().equals(currentUserId)) {
            return AjaxResult.error("无权访问此订单");
        }

        return success(order);
    }

    /**
     * 新增订单详情
     */
    @PreAuthorize("@ss.hasPermi('site:details:add')")
    @Log(title = "订单详情", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody OrderDetails orderDetails)
    {
        return toAjax(orderDetailsService.insertOrderDetails(orderDetails));
    }

    /**
     * 修改订单详情
     */
    @PreAuthorize("@ss.hasPermi('site:details:edit')")
    @Log(title = "订单详情", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody OrderDetails orderDetails)
    {
        return toAjax(orderDetailsService.updateOrderDetails(orderDetails));
    }

    /**
     * 删除订单详情
     */
    @PreAuthorize("@ss.hasPermi('site:details:remove')")
    @Log(title = "订单详情", businessType = BusinessType.DELETE)
	@DeleteMapping("/{orderIds}")
    public AjaxResult remove(@PathVariable Long[] orderIds)
    {
        return toAjax(orderDetailsService.deleteOrderDetailsByOrderIds(orderIds));
    }

    /**
     * 提交订单 (从购物车创建)
     */
    @Log(title = "订单", businessType = BusinessType.INSERT)
    @PostMapping("/submit")
    public AjaxResult submitOrder()
    {
        Long currentUserId = null;
        try {
            LoginUser loginUser = tokenService.getLoginUser(getRequest());
            currentUserId = loginUser.getUserId();
        } catch (Exception e) {
            return AjaxResult.error("用户未登录或会话无效");
        }

        if (currentUserId == null) {
            return AjaxResult.error("用户ID解析失败，请重新登录");
        }

        try {
            OrderDetails order = orderDetailsService.createOrderFromCart(currentUserId);
            return success(order);
        } catch (ServiceException e) {
            return AjaxResult.error(e.getMessage());
        } catch (Exception e) {
            // 记录日志
            return AjaxResult.error("创建订单失败，请稍后重试");
        }
    }

    /**
     * 单品立即购买 (跳过购物车)
     */
    @Log(title = "订单", businessType = BusinessType.INSERT)
    @PostMapping("/instant-buy")
    public AjaxResult instantBuy(@RequestBody InstantBuyRequest request)
    {
        Long currentUserId = null;
        try {
            LoginUser loginUser = tokenService.getLoginUser(getRequest());
            currentUserId = loginUser.getUserId();
        } catch (Exception e) {
            return AjaxResult.error("用户未登录或会话无效");
        }

        if (currentUserId == null) {
            return AjaxResult.error("用户ID解析失败，请重新登录");
        }

        if (request.getProductId() == null || request.getProductType() == null) {
            return AjaxResult.error("产品信息不完整。");
        }

        try {
            // 调用新的 Service 方法
            OrderDetails order = orderDetailsService.createOrderForSingleItem(
                    currentUserId,
                    request.getProductType(),
                    request.getProductId(),
                    request.getLicenseOption() != null ? request.getLicenseOption() : "standard"
            );
            return success(order);
        } catch (ServiceException e) {
            return AjaxResult.error(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("创建立即购买订单失败，请稍后重试");
        }
    }
}
